import axios from "axios";
import { showToast } from "vant";

const request = axios.create({
  timeout: 3000,
  baseURL: import.meta.env.VITE_API_BASE_URL,
});

request.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  (response) => {
    // data - 接口响应
    const { data } = response;
    // status - 业务状态码，msg - 业务状态描述
    const { status, msg } = data;

    switch (status) {
      case 0:
        // 成功
        return data.data;

      default:
        // 失败
        showToast({ message: msg || "有问题了" });
        return Promise.reject(msg);
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * apiGet
 * @param apiCode 请求头中 x-host 的值
 * @param params 请求参数 ?号参数
 * @example
 *    apiGet('mall.film-ticket.film.list', {
 *      cityId: '',
 *      pageNum: 1,
 *      pageSize: 10
 *    })
 */
export function apiGet<T = any>(apiCode: string, params?: any, headers?: any) {
  return request<any, T>({
    method: "GET",
    params,
    headers: {
      ...headers,
      "X-Host": apiCode,
    },
  });
}

/**
 *
 * @param apiCode 请求头中 x-host 的值
 * @param data 请求体参数
 * @example
 *    apiPost('mall.film-ticket.film.list', {
 *      cityId: '',
 *      pageNum: 1,
 *      pageSize: 10
 *    })
 */
export function apiPost(apiCode: string, data: any) {
  return request({
    method: "POST",
    data,
    headers: {
      "X-Host": apiCode,
    },
  });
}

// 默认导出
export default request;
